import uuid

from aiogram import F, Router, types
from aiogram.fsm.context import FSMContext

from tinkoff_bot.infrastructure.tinkoff_kassa.api import TinkoffKassa
from tinkoff_bot.infrastructure.tinkoff_kassa.enums.payment import PaymentStatus
from tinkoff_bot.tg_bot.keyboards.inline import CheckPaymentCF, get_payment_kb
from tinkoff_bot.tg_bot.keyboards.reply import get_main_menu_kb
from tinkoff_bot.tg_bot.states import BuyTicketSG

router = Router()


@router.callback_query(F.data == "participate")
async def create_payment_for_ticket(call: types.CallbackQuery, state: FSMContext, payment_client: TinkoffKassa):
    order_id = uuid.uuid4()
    payment = await payment_client.init_payment(100 * 100, str(order_id))
    await call.message.answer(
        f"Оплатите счет за сумму 100 руб", reply_markup=get_payment_kb(payment.paymenturl, payment.paymentid)
    )
    await state.update_data({"payment_id": payment.paymentid})

    await state.set_state(BuyTicketSG.waiting_for_payment)


@router.callback_query(CheckPaymentCF.filter())
async def check_payment(call: types.CallbackQuery, state: FSMContext, payment_client: TinkoffKassa):
    state_data = await state.get_data()
    payment = await payment_client.get_payment_status(state_data.get("payment_id"))
    payment_status = payment.status

    if isinstance(payment_status, str) or payment_status == PaymentStatus.NEW:
        await call.answer("Ожидаю зачисления")
        return
    elif payment_status in {
        PaymentStatus.AUTH_FAIL,
        PaymentStatus.CANCELED,
        PaymentStatus.DEADLINE_EXPIRED,
        PaymentStatus.REJECTED,
    }:
        await call.message.answer("Оплата неудачна")
        return
    else:
        await call.message.answer("Оплата удачна! Спасибо за покупку", reply_markup=get_main_menu_kb())
        await state.clear()
